package org.cuatrovientos.erp.dao;
/**
 * 
 */


import java.util.List;

import org.cuatrovientos.erp.model.Currency;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author eneko_lana
 *
 */
/**
 * implementation of CurrencyDAOInterface
 * @author VB
 *
 */
public class CurrencyDAO implements CurrencyDAOInterface {

	@Autowired
	 private SessionFactory sessionFactory;
	

	/**
	 * default constructor
	 */
	public CurrencyDAO () {
		
	}
	
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	
	/* 
	 * selects one Currency by Id
	 * @param id
	 * @return Currency
	 */
	 @Transactional(readOnly = true)
	public Currency selectById(int id) {
		 Currency Currency = (Currency) getSession().get(Currency.class, id);
	    return Currency;
	}

	/*
	 * retrieves all Currencys from db
	 * @return List of Currencys
	 */
	 @Transactional(readOnly = true)
	 public List<Currency> selectAll() {
	 
	    List<Currency> Currencys = getSession().createQuery("from currency").list();
	    return Currencys;
	}
	
	/*
	 * retrieves all Currencys from db
	 * @return List of Currencys
	 */
	 @Transactional(readOnly = true)
	public int selectAllCount() {
	    List<Currency> Currencys = getSession().createQuery("from currency").list();
	    return Currencys.size();
	}

	/*
	 * inserts a new Currency in database
	 * retrieves generated id and sets to Currency instance
	 * @param new product
	 */
	 @Transactional
	public void insert(Currency Currency) {
	    Integer id = (Integer) getSession().save(Currency);
	    Currency.setId(id);           
	}

	/*
	 * updates Currency
	 * @param Currency to update
	 */
	 @Transactional
	public void update(Currency Currency) {
		getSession().merge(Currency);
	}

	/*
	 * delete given Currency
	 * @param Currency to delete
	 */
	 @Transactional
	public void delete(Currency Currency) {
		getSession().delete(Currency);
	}

	 @Transactional
	public void saveOrUpdate(Currency Currency) {

		getSession().saveOrUpdate(Currency);
		
	}

	 /**
	  * deletes using id
	  */
	 @Transactional
	public void deleteById(int id) {
		 Currency Currency = (Currency) getSession().load(Currency.class,id);
		 getSession().delete(Currency);
	}

	 /**
	  * performs search operation
	  */
	 @Transactional(readOnly = true)
	public List<Currency> search(String name) {
		   Query query = getSession().createQuery("from currency s where s.name like :name");
           query.setParameter("name", "%"+name+"%");
           
           List<Currency> names = query.list();
		
           return names;
	}

}
